﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Singer.Framework.CoreDI
{
    public static class CoreDIServiceExtensions
    {
        /// <summary>
        /// 将程序集带有CoreDI特性的服务依赖注入
        /// </summary>
        public static void AddCoreDIServices(this IServiceCollection services, Assembly assembly)
        {
            foreach (Type type in assembly?.GetTypes().Where(x => x.GetCustomAttribute<CoreDIAttribute>() != null) ?? new Type[0])
            {
                CoreDIAttribute di = type.GetCustomAttribute<CoreDIAttribute>()!;
                if (di.InterfaceType != null && !type.GetInterfaces().Any(x => x == di.InterfaceType))
                    throw new Exception($"【CoreDI】 The Service '{type?.Name}' can not be resolving to the Service '{di.InterfaceType.Name}' ");
                services.Replace(new ServiceDescriptor(di.InterfaceType ?? type, type, (ServiceLifetime)di.LifeTimeType));
            }
        }
    }
}
